import React, { useEffect, useCallback, useReducer, Dispatch, memo, forwardRef, useMemo, useState } from 'react';
import { Title } from '@/components/common'
import { EditStatus } from 'gantd';
import { notification } from 'antd'
import LoupeSelect from '@/components/form/loupeselect';
import { searchFormschema, searchUISchema, columns, customComponents } from './schema'
import { ActionType, StateType, initState, reducer } from '../codelistselector/reducer'
import { getTreeData, getTreeDataSelect } from './utils'
import { fetchUnitListApi } from './service';
import { commonText } from '@/utils/utils'
/**
 * 单位选择器
 */
export interface UnitSelectorProps {
	value?: string | string[],
	onChange?: (value: string | string[]) => void,
	// multiple?: boolean,
	defaultValue?: string | string[],
	edit?: EditStatus.EDIT | EditStatus.CANCEL | EditStatus.SAVE,
	title?: string,
	defaultParams?: object,
}
function UnitSelector(props: UnitSelectorProps, ref: any) {
	const { defaultValue, value: _value, onChange, edit = EditStatus.EDIT, defaultParams = {}, title = tr("单位查询"), ...otherProps } = props;

	const [state, dispatch]: [StateType, Dispatch<ActionType>] = useReducer(reducer, initState);

	const { value, dropDownData, modalData, loading, filterInfo } = state;

	const [visible, setVisible] = useState(false);

	const queryBySelect = useCallback(async () => {
		const data = await fetchUnitListApi({ ...initState.params, ...defaultParams });
		const treeData = getTreeDataSelect(data)
		dispatch({ type: "saveDropDownData", payload: treeData });
	}, [defaultParams])

	useEffect(() => {
		dispatch({ type: "saveValue", payload: _value });
	}, [_value])

	useEffect(() => {
		defaultValue && dispatch({ type: "saveValue", payload: defaultValue });
		queryBySelect()
	}, [])

	//改变弹窗状态
	const changeVisibleState = useCallback((visible = false) => {
		setVisible(visible);
	}, []);

	const queryByModal = useCallback(async (params) => {
		dispatch({ type: "save", payload: { loading: true } });
		const data = await fetchUnitListApi({ ...params, ...defaultParams });
		data.map((item: any) => {
			const parentExist = data.find((ele: any) => ele.id == item.parentId)
			if (parentExist) {
				item.path = item.parentId ? [item.parentId, item.id] : [item.id]

			} else {
				item.path = [item.id]
			}
		})
		dispatch({ type: 'save', payload: { modalData: data, loading: false, filterInfo: { ...params } } })
	}, [defaultParams])

	useEffect(() => {
		dispatch({ type: "save", payload: visible });
	}, [visible])

	const onModalVisibleChange = useCallback(async (visible) => {
		visible ? queryByModal(initState.params) : dispatch({ type: "initModal" })
	}, [visible, setVisible])

	const onSearch = useCallback((searchParams) => {
		queryByModal({ ...searchParams });
	}, [filterInfo])

	const onValueChange = useCallback((value, record) => {
		if (typeof record == 'object') {
			if (record[0].parentId || typeof record[0] != 'object') {
				dispatch({ type: "save", payload: value });
				if (onChange) onChange(value)
				setVisible(false)
			} else {
				notification['warning']({
					message: tr('提示'),
					description: tr(`请选择正确的单位`),
					duration: 3
				})
			}
		}


	}, [onChange])


	return <LoupeSelect
		selectorId='demoLoupe'
		value={value}
		treeData={dropDownData}
		useCache={false}
		edit={edit}
		labelProp='name'
		valueProp="id"
		onChange={onValueChange}
		componentType="TreeSelect"
		multiple={false}
		onLoupeClick={changeVisibleState.bind(null, true)}

		{...otherProps}

		viewProps={{
			searchFormTitle: <Title title={commonText.smartSearchTitleText} showShortLine />,
			title: <Title title={title} />,
			columns,
			itemState: { width: 800, height: 600 },
			onModalVisibleChange,
			viewKey: 'unitSelector',
			uiSchema: searchUISchema,
			schema: searchFormschema,
			customComponents: customComponents,
			dataSource: modalData,
			loading: loading,
			onSearch,
			rowkey: 'id',
			key: 'path',
			treeData: true,
			groupSuppressAutoColumn: true,
			getDataPath: (data: any) => data.path,
			visible: visible,
			multiple: false,
			onCancel: changeVisibleState.bind(null, false)


		}
		}
	/>
}

export default memo(forwardRef(UnitSelector))